<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <video src="" id="video"></video>
    <canvas id="canvas" width="300" height="300"> </canvas>
    <button id="save">保存当前点数据</button>
    <button id="judge">判断</button>
    <script>

        let video = document.querySelector("#video")
        let canvas = document.querySelector("#canvas")
        let context = canvas.getContext("2d");
        let canvasData 
        function cameraStart() {
            let isFront = false;

            let config = {
                audio: false, video: true, video: {
                    width: 300,
                    height: 300,
                    facingMode: isFront ? "user" : "environment",
                    frameRate: { ideal: 30, max: 30 }
                },
            };
            
            function successCallback(stream) {
                // 将返回的流提供给控制台进行检查
                // console.log(stream)
                video.srcObject = stream;
                // 播放
                video.play();
            }

            // 传入3个参数，第一个是配置，第二个是成功的回调
            // 这个更加规范了，多加了一个mediaDevices。window.navigator.getUserMedia(config, successCallback, errorCallback);
            navigator.mediaDevices.getUserMedia(config)
                .then(function (stream) {
                    successCallback(stream)
                })

            video.oncanplay = function () {
                video.play();
                switchToCanvas();
            }
        }

        function switchToCanvas() {
            // 将video上的图片的每一帧以图片的形式绘制的canvas上
            context.drawImage(video, 0, 0, 300, 300);
            const video_image_data = context?.getImageData(0, 0, canvas.width, canvas.height);
            const imageData = new ImageData(video_image_data.width, video_image_data.height)
            canvasData = video_image_data.data;
            window.requestAnimationFrame(switchToCanvas);
        }
        // 调用
        cameraStart()



        let prev = []
        document.querySelector("#save").addEventListener("click",()=>{
            prev = []
            // console.log(canvasData.length,"length")
            let center = 0
            for (let i = 0+center; i < canvasData.length-center; i += 4) {
            // 基底素材的pixel
                const vr = canvasData[i] ;
                const vg = canvasData[i + 1] ;
                const vb = canvasData[i + 2] ;
                // const va = canvasData[i + 3] *100;
                // console.log(vr,vg,vb,va)
                prev.push([vr,vg,vb])
            }
            console.log("保存当前点成功")
            // alert(2)
        })

        let vector = []
        document.querySelector("#judge").addEventListener("click", () => {
            vector = []
            let center = 0
            for (let i = 0+center; i < canvasData.length-center; i += 4) {
            // 基底素材的pixel
                const vr = canvasData[i];
                const vg = canvasData[i + 1];
                const vb = canvasData[i + 2];
                // const va = canvasData[i + 3];
                // console.log(vr,vg,vb,va)
                vector.push([vr,vg,vb])
            }
            // console.log(prev,vector,)   
            let similarRes = 0
            for(let i in prev){
                let temp =  minkowski_distance(255,0,prev[i], vector[i])
                // console.log("相似度参数：",temp)
                similarRes += temp
            }
            console.log("相似度",similarRes/prev.length,)
           
        })



        /**
         *
            高斯距离（标准化欧氏距离）：计算两个向量间的相似程度，值越大，相似度越高        
        */
        function minkowski_distance(max,min,param_a,param_b){
	if(param_a.length != param_b.length){
		return "你参数之间的长度应该要相等"
	}
	let max_distance_param = Math.pow((max-min),2)
	let max_distance = 0
	for(let i in param_a){
		max_distance =  max_distance_param + max_distance
	}

	let param_distance = 0
	for(let i in param_a){
		param_distance += Math.pow(param_a[i] - param_b[i],2)

	}
	let result =( max_distance-param_distance) / max_distance
	return (result)

}


        /*
        [[1,3],[2,4]]
        */
        function cosine_similarity(param_a, param_b) {
            // 求点积
            // console.log(param_a, param_b, param_a.length)
            let plus_sum = 0;
            for (let i = 0; i < param_a.length; i++) {
                let tempAB = param_a[i] * param_b[i];
                plus_sum += tempAB;
            }
            // 求 A 模长
            let paramA_temp_length = 0;
            for (let i = 0; i < param_a.length; i++) {
                paramA_temp_length += Math.pow(param_a[i], 2);
            }
            let paramA_length = Math.pow(paramA_temp_length, 0.5);

            // 求 B 模长
            let paramB_temp_length = 0;
            for (let i = 0; i < param_a.length; i++) {
                paramB_temp_length += Math.pow(param_b[i], 2);
            }
            let paramB_length = Math.pow(paramB_temp_length, 0.5);
            let result = plus_sum / (paramA_length * paramB_length);
            return result;
        }
    </script>
</body>

</html>